﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Sunlight : MonoBehaviour
{
    // Start is called before the first frame update
    private float downPositionY;//下落的目标点纵坐标
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //天空阳光的停止
        if (transform.position.y <= downPositionY)
        {
            Invoke("destroySunlight", 5);
            return;
        };
        transform.Translate(Vector3.down * Time.deltaTime);
    }
    
    //实现阳光自然消亡
    private void OnMouseDown()
    {
        PlayerManager.Instance.SunNum += 25;
        Vector3 sunNum = Camera.main.ScreenToWorldPoint(UIManager.Instance.GetSunTextPos());
        sunNum = new Vector3(sunNum.x, sunNum.y, 0);
        Fly(sunNum);
        
    }
    //阳光飞向计分板的动画
    private void Fly(Vector3 pos)
    {
        StartCoroutine(DoFly(pos));
    }

    private IEnumerator DoFly(Vector3 pos)
    {
        Vector3 direction = (pos - transform.position).normalized;
        while (Vector3.Distance(pos, transform.position) >= 1f)
        {
            yield return new WaitForSeconds(0.01f);
            transform.Translate(direction);

        }
        destroySunlight();
    }
    //阳光从向日葵生成的部分
    public void Jump()
    {

        StartCoroutine(doJump());
    }

    private IEnumerator doJump()
    {
        
        bool isLeft = Random.Range(0, 2) == 0;
        Vector3 starPos = transform.position;

        if (isLeft)
        {
            while(transform.position.y < starPos.y+1){
                yield return new WaitForSeconds(0.005f);
                transform.Translate(new Vector3(-0.01f, 0.05f, 0));

            }
            while(transform.position.y > starPos.y){
                yield return new WaitForSeconds(0.005f);
                transform.Translate(new Vector3(-0.01f, -0.05f, 0));

            }
        }
        else
        {
            while (transform.position.y <= starPos.y + 1)
            {
                yield return new WaitForSeconds(0.005f);
                transform.Translate(new Vector3(0.01f, 0.05f, 0));

            }
            while (transform.position.y >= starPos.y)
            {
                yield return new WaitForSeconds(0.005f);
                transform.Translate(new Vector3(0.01f, -0.05f, 0));

            }
        }
    }
    //阳光消失
    private void destroySunlight()
    {
        Destroy(gameObject);
    }
    //天空阳光的脚本
    public void InitForSky(float downPositionY, float CreatPosX, float CreatPosY)
    {
        this.downPositionY = downPositionY;
        transform.position = new Vector2(CreatPosX, CreatPosY);
    }
}
